//
//  XZ_KvcAndKvoController.m
//  Project_Demo
//
//  Created by caoxiaozhu on 2018/7/24.
//  Copyright © 2018年 caoxiaozhu. All rights reserved.
//

#import "XZ_KvcAndKvoController.h"
#import "PersonKVC.h"
#import "Author_KVC.h"
#import "Book_KVC.h"

@interface XZ_KvcAndKvoController ()

@end

@implementation XZ_KvcAndKvoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self test1];
    [self test2];
}

-(void)test1{
    //Kvc 直接设置对象的值
    PersonKVC *p  = [PersonKVC new];
    //这里setValue方法：第一个参数是value,第二个参数是key(就是类的属性名称)
    [p setValue:@"caoxiaozhu" forKey:@"name"];
    //设置基本数据类型
    //这里需要将基本类型转化成NSNumber
    //在设置值的时候，会有自动解包的过程，NSNumber会解包赋值给age
    [p setValue:@22 forKey:@"age"];
    NSString *name = [p valueForKey:@"name"];
    NSNumber* age = (NSNumber *)[p valueForKey:@"age"];
    NSLog(@"name==>%@,age==>%@",name,age);
    
    //数据持久化
//    [kUserDefaults setValue:@"" forKey:@""];
}

-(void)test2{
    //--------------------KVC的运算
    Author_KVC *author = [[Author_KVC alloc] init];
    [author setValue:@"莫言" forKeyPath:@"name"];
    
    Book_KVC *book1 = [[Book_KVC alloc] init];
    book1.name = @"红高粱";
    book1.price = 9;
    Book_KVC *book2 = [[Book_KVC alloc] init];
    book2.name = @"蛙";
    book2.price = 10;
    NSArray *array = [NSArray arrayWithObjects:book1,book2, nil];
    [author setValue:array forKeyPath:@"issueBook"];
    
    //基本数据类型会自动被包装成NSNumber，装到数组中
    //得到所有书籍的价格
    NSArray *priceArray = [author valueForKeyPath:@"issueBook.price"];
    NSLog(@"%@",priceArray);
    
    //获取数组的大小
    NSNumber *count = [author valueForKeyPath:@"issueBook.@count"];
    NSLog(@"count=%@",count);
    
    //获取书籍价格的总和
    NSNumber *sum = [author valueForKeyPath:@"issueBook.@sum.price"];
    NSLog(@"%@",sum);
    
    //获取书籍的平均值
    NSNumber *avg = [author valueForKeyPath:@"issueBook.@avg.price"];
    NSLog(@"%@",avg);
    
    //获取书籍的价格最大值和最小值
    NSNumber *max = [author valueForKeyPath:@"issueBook.@max.price"];
    NSLog(@"%@",max);
    NSNumber *min = [author valueForKeyPath:@"issueBook.@min.price"];
    NSLog(@"%@",min);
    
    
}

@end
